from flask import render_template,redirect,url_for,session, flash, request
from flask_login import login_required, current_user
#from flaskext.uploads import UploadSet, IMAGES
from bson.dbref import DBRef

from controller import app
from lib.form import Form

from model.company import CompanyDao

from service.company import CompanyForm, CompanyService
import json

IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())

class CompanysForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)

@app.route('/manage_companies')
@app.route('/manage_companies', methods=['GET','POST'])
@login_required
def manage_companies():
    form = CompanyForm()
    session['errors_json'] = ''
    if form.is_submitted():
        if form.has_error():
            session['errors_json'] = json.dumps(form.errors)
            return redirect(url_for('display_companies'))#errors_json=json.dumps(form.errors)))
        else:
            service = CompanyService()
            service.submit_company(form)
            return redirect(url_for('display_companies'))
    else:
        return redirect(url_for('display_companies'))

@app.route('/display_companies')
@login_required
def display_companies():
    #return render_template("add_company-v1.html", companies=None)
    if session['errors_json'] == '':
        errors = []
    else:
        errors = session['errors_json']
    
    service = CompanyService()
    user = service.get_current_user()
    _companies = []
    if user['role'] == 2:
        _companies = service.get_companies()
    else:
        user_ref = DBRef('users', current_user._id)
        _companies = service.get_companies({'admin':user_ref})

    return render_template("manage_companies.html", errors_json=errors, companies=_companies, user=user)